import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'ble_scan_result.dart';
import 'image_deal_with.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MethodChannelDemo(title: '交互测试-Android'),
    );
  }
}

class MethodChannelDemo extends StatefulWidget {
  const MethodChannelDemo({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MethodChannelDemo> createState() => _MethodChannelDemoState();
}

class _MethodChannelDemoState extends State<MethodChannelDemo> {
  var channel = const MethodChannel('com.example.ble_test.MethodChannel');

  late Uint8List dataTest;
  // ignore: prefer_typing_uninitialized_variables
  BleScanResultListModel _nativeData = BleScanResultListModel.fromJson([]);

  String status = "";

  @override
  void initState() {
    super.initState();
    channel.setMethodCallHandler((call) {
      setState(() {
        if(call.method=="scanResult"){
          String result = call.arguments['result'];
          _nativeData = BleScanResultListModel.fromJson(json.decode(result));
        }
        if(call.method=="device"){
          status = call.arguments['status'];
        }
        if(call.method=="audio"){
          status += "\n" + call.arguments['data'];
          status += call.arguments['time'];
        }
      });
      return returnToRaw();
    });
  }

  @override
  Widget build(BuildContext context) {
    double statusBarHeight = MediaQueryData.fromWindow(ui.window).padding.top;
    var image =Image
        .network("http://img.netbian.com/file/2022/1016/000735dKYSm.jpg")
        .image;;
    return Scaffold(
        body: Padding(
            padding: EdgeInsets.only(top: statusBarHeight),
            child: Column(
              children: [
                SizedBox(
                    height: 100,
                    child: SingleChildScrollView(
                      child: Text(status),
                    )
                ),
                DecoratedBox(
                    decoration: const BoxDecoration(color: Colors.white70),
                    child: SizedBox(
                        height: 100,
                        child: ListView.builder(
                            itemCount: _nativeData.data.length,
                            itemBuilder: (BuildContext context, int index) {
                              return Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
                                Text("name:${_nativeData.data[index].name}   rssi:${_nativeData.data[index].rssi}"),
                                TextButton(
                                    onPressed: (){
                                      channel.invokeMethod('connect',{"address":_nativeData.data[index].device});
                                    },
                                    child: const Text("连接",style: TextStyle(color: Colors.yellow))
                                )
                              ]);
                            }
                        )
                    )

                ),
                TextButton(
                  child: const Text('开始扫描'),
                  onPressed: () {
                    channel.invokeMethod('scan');
                  },
                ),
                TextButton(
                  child: const Text('发送测试数据'),
                  onPressed: () async {
                    status = "${DateTime.now().millisecondsSinceEpoch}";
                    status += "大小${dataTest.length}";
                    var rt = await channel.invokeMethod('sendData',{"data": dataTest});
                    setState(() {
                      status += rt["data"];
                    });
                  },
                ),
                TextButton(
                  child: const Text('获取测试数据'),
                  onPressed:() async {
                    setState(() {
                      status = "获取中";
                    });
                    //http://img.netbian.com/file/2022/1016/000735dKYSm.jpg 3782591
                    //https://mmbiz.qpic.cn/mmbiz_jpg/FvfC3vlk8JxBulJKA1m8CxSkqUfJAAk6qat8HsRj7n9wzrSicvCgLJ7ZSMxBxeUicsickTm0l2cPQ6sEEoOh7TBrQ/640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1&wx_co=1 1851168
                    //https://mmbiz.qpic.cn/mmbiz_jpg/FvfC3vlk8JxBulJKA1m8CxSkqUfJAAk6hG7ha0BhTURkktIKj7J0JaWFyU6ibT5WPTS0EscT7nib0S2dqcH62bfw/640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1&wx_co=1 592971
                    //https://img2022.cnblogs.com/blog/1619947/202208/1619947-20220815113045928-772032989.gif 14730
                    ui.Image uiImage = await loadImageByProvider(image,context);
                    var toByteData = await uiImage.toByteData(format: ui.ImageByteFormat.png);
                    setState(() {
                      dataTest = toByteData!.buffer.asUint8List();
                      status = "已获取lengthInBytes:${dataTest.lengthInBytes}length:${dataTest.length}";
                    });
                  },
                ),
                MyImage(imageProvider:image),
              ],
            )
        )
    );
  }

  Future<String> returnToRaw() async {
    return 'received your message';
  }
  static Future<ui.Image> loadImageByProvider(ImageProvider provider, BuildContext context) async {
    Completer<ui.Image> completer = Completer<ui.Image>(); //完成的回调

    late ImageStreamListener listener;
    ImageStream stream = provider.resolve(createLocalImageConfiguration(context)); //获取图片流
    listener = ImageStreamListener((ImageInfo frame, bool sync) {
      //监听
      final ui.Image image = frame.image;
      completer.complete(image); //完成
      stream.removeListener(listener); //移除监听
    });
    stream.addListener(listener); //添加监听
    return completer.future; //返回
  }


}